package team.tunan.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import team.tunan.common.HttpCodeEnum;
import team.tunan.dto.SupplierPageDto;
import team.tunan.entity.Supplier;
import team.tunan.exception.BusinessException;
import team.tunan.mapper.SupplierMapper;
import team.tunan.service.ISupplierService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.List;

import static team.tunan.utils.BaseRegexPatterns.EMAIL_REGEX;
import static team.tunan.utils.BaseRegexPatterns.PHONE_REGEX;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author sqx
 * @since 2023-12-24
 */
@Service
public class SupplierServiceImpl extends ServiceImpl<SupplierMapper, Supplier> implements ISupplierService {

    @Autowired
    private SupplierMapper supplierMapper;

    @Override
    public int insertSupplier(Supplier supplier) {
        //checkSupplier(supplier);
        return supplierMapper.insert(supplier);
    }

    @Override
    public int updateSupplier(Supplier supplier) {
        //checkSupplier(supplier);
        return supplierMapper.updateById(supplier);
    }

    @Override
    public int deleteSupplier(String id) {
        return supplierMapper.deleteById(id);
    }



    @Override
    public Page<Supplier> selectPage(SupplierPageDto supplierPageDto) {
        LambdaQueryWrapper<Supplier> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        if(StringUtils.isNotBlank(supplierPageDto.getAddress())&&!"null".equals(supplierPageDto.getAddress())){
            lambdaQueryWrapper.like(Supplier::getAddress,supplierPageDto.getAddress());
        }
        if(StringUtils.isNotBlank(supplierPageDto.getSupplierName())&&!"null".equals(supplierPageDto.getSupplierName())){
            lambdaQueryWrapper.like(Supplier::getSupplierName,supplierPageDto.getSupplierName());
        }
        Page page = new Page(supplierPageDto.getCurrentPage(), supplierPageDto.getPageSize());
        Page page1 = supplierMapper.selectPage(page, lambdaQueryWrapper);
        return page1;
    }

    private void checkSupplier(Supplier supplier){
        if(supplier.getSupplierName()==null||supplier.getSupplierName().equals("")){
            throw new RuntimeException("供应商名称不能为空");
        }
        if(supplier.getEmail().matches(EMAIL_REGEX)) {
            throw new BusinessException(HttpCodeEnum.OPERATION_ERROR.getCode(), "邮箱格式错误，请重新输入");
        }
        if(supplier.getContactNumber().matches(PHONE_REGEX)) {
            throw new BusinessException(HttpCodeEnum.OPERATION_ERROR.getCode(), "手机号格式错误，请重新输入");
        }
    }
}
